package com.qianniu.napi.admin.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.Health;
import com.qianniu.napi.admin.entity.User;
import com.qianniu.napi.admin.service.IHealthService;
import com.qianniu.napi.admin.service.IUserService;
import com.qianniu.napi.common.util.AddressUtils;
import com.qianniu.napi.common.util.CardUtil;
import com.qianniu.napi.common.util.WeixinUtil;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Configuration
@Component // 此注解必加
@EnableScheduling // 此注解必加
public class UserTask {

    private static final Logger logger = LoggerFactory.getLogger(UserTask.class);

    @Autowired
    private IUserService userService;
    @Autowired
    private IHealthService healthService;

    //更新用户设备相关信息【每小时更新一次】
    //通过ud字段
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void refreshUser() {
        logger.debug(">>>refreshStock exe success");
        List<User> list = userService.selectList(new EntityWrapper<User>().setSqlSelect("id,ud,ip").isNull("brand")
                .isNotNull("ud").isNotNull("ip"));

        try {
            for (User user : list) {
                if (!Strings.isNullOrEmpty(user.getUd())) {
                    // iPhone_iPhone 6s Plus<iPhone8,2>_ios_iOS 11.4.1_7.0.1
                    String[] uds = user.getUd().split("_");
                    if (uds.length == 5) {
                        user.setBrand(uds[0]);
                        user.setModel(uds[1]);
                        user.setPlatform(uds[2]);
                        user.setSystem(uds[3]);
                        user.setSysversion(uds[4]);
                    }
                }
                user.setLocation(AddressUtils.getCityInfo(user.getIp()));
                user.updateById();
            }
        } catch (Exception e) {
            logger.error("======refreshUser error", e);
        }
        logger.debug(">>>refreshUser exe success");
    }

    //重新计算刷新微信用户图像
    @Scheduled(cron = "0 20 17 * * ?")
    public void refreshUserHeadimg() {
        logger.debug(">>>refreshUserHeadimg start");

        HttpGet httpget = null;
        try {
            Integer index = 1;
            Integer limit = 100;
            boolean flag = true;
            HttpClient httpclient = HttpClients.createDefault();
            StringBuilder sb = null;

            while (flag) {
                Wrapper<User> wrapper = new EntityWrapper<User>()
//                        .setSqlSelect("id,avatar_pic avatarPic,openid,mpid").eq("mpid", 17).eq("id", 2837);
                        .setSqlSelect("id,avatar_pic avatarPic,openid,mpid").eq("mpid", 30).eq("id", 1081);

                Page page = new Page(index, limit);
                Page<User> list = userService.selectPage(page, wrapper);

                logger.debug(">>>>>>>>>>>>>>>>>>checkStoreImage list=" + JSON.toJSONString(list.getRecords()));

                for (User item : list.getRecords()) {
                    logger.info("------------------------------for each start");
                    if (Strings.isNullOrEmpty(item.getAvatarPic()) || item.getMpid() == null || Strings.isNullOrEmpty(item.getOpenid()))
                        continue;

                    httpget = new HttpGet(item.getAvatarPic());
                    HttpResponse response = httpclient.execute(httpget);

                    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                        String content = "httpGet failed,url:" + item.getAvatarPic() + ",http StatusCode:" + response.getStatusLine().getStatusCode();
                        logger.error(content);
                    } else {
                        if (response.getFirstHeader("X-ErrNo") != null) {
                            logger.info("------------------------------response.getFirstHeader(X-ErrNo)=" + response.getFirstHeader("X-ErrNo"));
                            JSONObject json = WeixinUtil.getWXUserInfo(item.getOpenid(), item.getMpid().toString());
                            logger.info("------------------------------json=" + JSON.toJSONString(json));

                            if (json.containsKey("avatarUrl")) {
                                item.setAvatarPic(json.getString("avatarUrl"));
                                item.updateById();
                            }
                        }
                    }
                }
                flag = list.getRecords() != null && list.getRecords().size() == limit;
                index++;
            }
        } catch (Exception e) {
            logger.error("======refreshUser error", e);
        } finally {
            httpget.releaseConnection();
        }
        logger.debug(">>>refreshUser exe success");
    }

    //每天刷新用户会员失效状态
    //该逻辑只针对普通用户会员
    @Scheduled(cron = "0 10 1 * * ?")
    public void refreshMemberStatus() {
        logger.debug("-------------refreshMemberStatus start");

        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        while (flag) {
            Wrapper<User> wrapper = new EntityWrapper<User>().eq("is_member", 1)
                    .gt("is_member", 0)
                    .eq("is_mch", -1).lt("is_platform", -1)
                    .eq("is_daogou", -1).lt("is_staff", -1)
                    .eq("is_agent", -1).lt("is_admin", -1);

            Page page = new Page(index, limit);
            Page<User> list = userService.selectPage(page, wrapper);

            for (User item : list.getRecords()) {

                Date now = new Date();
                try {
                    //按照天【yyyy-mm-dd】来判断过期
                    if (now.getTime() > item.getEndtime().getTime()) {
                        item.setState(-1);
                        item.setIsMember(-1);
                        item.setIsMember(-1);
                        item.setModifytime(now);
                        item.updateById();
                        logger.debug("--------------------CouponTask 333");
                    }
                    logger.debug("--------------------CouponTask 333444");
                } catch (Exception e) {
                    logger.debug("--------------------error");
                }
            }
            flag = list.getRecords() != null && list.getRecords().size() == limit;
            logger.debug("--------------------CouponTask 888 flag=" + flag);
            index++;
        }

        logger.debug("--------------------UserTask refreshMemberStatus exe success");
    }


//    //根据身份证号码刷新用户性别年龄失效状态
//    @Scheduled(cron = "0 49 9 * * ?")
//    public void refreshhealthinfo() {
//        logger.debug("-------------refreshMemberStatus start");
//
//        Wrapper<Health> wrapper = new EntityWrapper<Health>().eq("mpid", 11);
//
//        List<Health> list = healthService.selectList(wrapper);
//
//        for (Health item : list) {
//
//            if (Strings.isNullOrEmpty(item.getCardno()) || item.getCardno().length() != 18) continue;
//            try {
//
//                Map<String, Integer> map = CardUtil.getCarInfo(item.getCardno());
//                if (map.containsKey("age")) item.setAge(map.get("age"));
//                if (map.containsKey("sex")) item.setSex(map.get("sex"));
//                item.updateById();
//            } catch (Exception e) {
//                logger.error("refreshhealthinfo error", e);
//            }
//        }
//
//        logger.debug("--------------------UserTask refreshMemberStatus exe success");
//    }

}
